﻿using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using ChatRoom.ViewModel;
using ChatRoom.Protocol;
using GalaSoft.MvvmLight.Threading;

namespace ChatRoom.Tests.Client
{
    internal sealed class View : IChatRoomView
    {
        public void ShowErrorMsg(string message)
        {
            Console.WriteLine("!!! ERROR !!!: {0}", message);
        }
    }

    static class Program
    {
        static void Main(string[] args)
        {
            using (var viewModel = new ChatRoomViewModel("localhost", new View()))
            {
                viewModel.NeedSwitchContext = false;
                viewModel.PropertyChanged += OnPropertyChanged;
                viewModel.ChatMessages.CollectionChanged += ChatMessagesOnCollectionChanged;
                viewModel.OnLoaded();

                string text = Console.ReadLine();
                while (text != "exit")
                {
                    viewModel.TxtToSend = text;
                    viewModel.CmdSendChat.Execute(null);

                    text = Console.ReadLine();
                }
            }//using
        }

        private static void ChatMessagesOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs evtargs)
        {
            Debug.Assert(evtargs.Action == NotifyCollectionChangedAction.Add);
            foreach (object newItem in evtargs.NewItems)
            {
                ChatMessage msg = (ChatMessage)newItem;
                Console.WriteLine("[New Message]: '{0}' @ <{1}>", msg.Content, msg.Time.ToShortTimeString());
            }
        }

        private static void OnPropertyChanged(object sender, PropertyChangedEventArgs evtargs)
        {
            var viewmodel = (ChatRoomViewModel)sender;
            switch (evtargs.PropertyName)
            {
                case "IsConnected":
                    Console.WriteLine("IsConnected: {0}", viewmodel.IsConnected);
                    break;

                case "ClientInfos":
                    Console.WriteLine("************* CLIENT INFOS REFRESHED *************");
                    int index = 0;
                    foreach (var clientInfo in viewmodel.ClientInfos)
                    {
                        ++index;
                        Console.WriteLine("[{0}] <{1}:{2}>", index, clientInfo.Host, clientInfo.Port);
                    }
                    Console.WriteLine("************* END CLIENT INFOS REFRESHED *************");
                    break;

                case "TxtToSend":
                    break;

                default:
                    throw new InvalidOperationException("invalid property");
            }//switch
        }
    }
}
